package com.sunxd.limit.core.handlers.joinAct;

import com.alibaba.fastjson.JSON;
import com.sunxd.limit.core.annotation.LimitAnnotation;
import com.sunxd.limit.beans.constants.LimitAnnotationGroup;
import com.sunxd.limit.beans.constants.LimitAnnotationKey;
import com.sunxd.limit.beans.params.AbsRequest;
import com.sunxd.limit.beans.params.Context;
import com.sunxd.limit.beans.params.Limit;
import com.sunxd.limit.core.AbstractLimitHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

/**
 * @author sun.xd
 * @description: description
 * @date 2024/10/22 16:58
 */
@Slf4j
@Order(2)
@Component
@LimitAnnotation(key = LimitAnnotationKey.GROUP_LIMIT, group = LimitAnnotationGroup.ACTIVITY)
public class GroupLimitHandler extends AbstractLimitHandler {

    @Override
    public Boolean judge(Context context) {
        Limit limit = getLimit(context);
        AbsRequest request = context.getRequest();
        List<String> configList = (List<String>) limit.getValue();
        if (CollectionUtils.isEmpty(configList)) {
            return Boolean.TRUE;
        }
        for (String str : configList) {
            if (Objects.equals(request.getGroup(), str)){
                return Boolean.TRUE;
            }
        }
        log.info("GroupLimitHandler warm => configValue:{}, realValue:{} ", JSON.toJSONString(configList),request.getGroup());
        return Boolean.FALSE;
    }

    @Override
    public String key() {
        return LimitAnnotationKey.GROUP_LIMIT;
    }
}
